package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"shop/models"
	"strconv"
	"time"
)

type ShopController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	pageData := make(map[string]interface{})
	key := "shop-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		var count int64
		models.DB.Model(&models.Shop{}).Count(&count)
		offset := (page - 1) * size
		var shop []models.Shop
		err = models.DB.Offset(offset).Limit(size).Find(&shop).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		pageData["shop"] = shop
		pageData["count"] = count
		jsonByte, _ := json.Marshal(&pageData)
		value := string(jsonByte)
		models.Rdb.Set(key, value, time.Second*5)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-mysql",
			Data: pageData,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件过大，不可以超过2MB",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		img := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: img,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Add() {
	username := c.GetString("username")
	tel := c.GetString("tel")
	name := c.GetString("name")
	area := c.GetString("area")
	status := c.GetString("status")
	lx := c.GetString("lx")
	img := c.GetString("img")
	shop := models.Shop{
		UserName: username,
		Tel:      tel,
		Name:     name,
		Area:     area,
		Status:   status,
		Lx:       lx,
		Img:      img,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Shop{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
